package com.gxuwz.mxb.lph.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxuwz.mxb.lph.dao.MenuMapper;
import com.gxuwz.mxb.lph.dao.RoleMapper;
import com.gxuwz.mxb.lph.dao.RoleMenuMapper;
import com.gxuwz.mxb.lph.dao.UserRoleMapper;
import com.gxuwz.mxb.lph.entity.HouseholeMember;
import com.gxuwz.mxb.lph.entity.Role;

import com.gxuwz.mxb.lph.entity.RoleMenu;
import com.gxuwz.mxb.lph.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 根据角色ID查询角色信息
     */
    public Role findRoleByRoleId(String roleId){
        return roleMapper.findRoleByRoleId(roleId);
    }
    /**
     * 根据id 查询角色信息
     */
    public Role selectByPrimaryKey(Integer id){
        return roleMapper.selectByPrimaryKey(id);
    }
    /**
     * 查找角色列表
     */
    public PageInfo<Role> getRoleList(String roleName, Integer currentPage, Integer limit){
        //利用PageHelper分页查询 注意：这个一定要放查询语句的前一行,否则无法进行分页,因为它对紧随其后第一个sql语句有效
        PageHelper.startPage(currentPage,limit);
        List<Role> roleList = roleMapper.getRoleList(roleName);
        PageInfo<Role> pageInfo = new PageInfo<Role>(roleList);
        return pageInfo;
    }
    /**
     * 添加
     */
    public void addRole(Role role){
        role.setCreateTime(new Timestamp(System.currentTimeMillis()));
        role.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        roleMapper.insert(role);
    }

    /**
     *修改
     */
    public void edit(Role role){
        role.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        roleMapper.updateByPrimaryKey(role);
    }

    /**
     * 删除
     *
     */
    public void delete(Integer id){
        roleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据用户ID获取用户拥有菜单列表
     * @param userId
     * @return
     */
    public List<String> getUserPermissions(String userId) {
        List<String> strList=new ArrayList<String>();
        // 根据用户ID获取用户角色关联关系，即该用户拥有多少角色
        List<UserRole> userRoleList = userRoleMapper.getUserRoleList(userId);

        for (int i = 0; i < userRoleList.size(); i++){
            List<RoleMenu> roleRightList = new ArrayList<RoleMenu>();
            // 获取角色菜单关联关系，即角色拥有多少菜单
            roleRightList = roleMenuMapper.getRoleMenuList(userRoleList.get(i).getRoleId());
            for (int j = 0; j < roleRightList.size(); j++){
                strList.add(roleRightList.get(j).getMenuId());
            }
            System.out.println("RoleService--strList:"+strList);
        }
        return strList;
    }

}
